import { UploadExcel } from '@/api/taskPlanning/index'
import {
  PriorityOptions,
  whetherOption,
  missionTypeOption,
  targetShapeOption,
  weatherConditionOption
} from '@/assets/data/pathInfo'
import { CallIntelligentDecision } from '@/api/decisionManage/index.js'
import { SavePlanTasks } from '@/api/decisionManage/index.js'
import { compareDates } from '@/utils/index'
export default {
  components: {},
  data() {
    return {
      PriorityOptions,
      whetherOption,
      missionTypeOption,
      targetShapeOption,
      weatherConditionOption,
      visiable: false,
      dialogVisible1: false,
      dialogVisible2: false,
      labelPosition: 'right',
      formData: {
        rwlx: '',
        mbxt: '',
        qxtj: '',
        gjys: '',
        sfhzmb: '',
        zhlx: '',
        gzms: '',
        fbl: '',
        yxj: '',
        xqkssj: '',
        xqjssj: ''
      },
      rules: {
        xqmc: [
          { required: true, message: '请输入需求名称', trigger: 'blur' }
        ],
        rwlx: [{ required: true, message: '请输入任务类型', trigger: 'blur' }],
        mbxt: [{ required: true, message: '请输入目标形态', trigger: 'blur' }],
        qxtj: [
          {
            required: true,
            message: '请输入气象条件',
            trigger: 'blur'
          }
        ],
        gjys: [
          { required: true, message: '请选择攻击因素', trigger: 'change' }
        ],

        sfhzmb: [
          { required: true, message: '请选择合作目标', trigger: 'change' }
        ],
        xqkssj: [
          { required: true, message: '请选择需求开始时间', trigger: 'change' }
        ],
        xqjssj: [
          { required: true, message: '请选择需求结束时间', trigger: 'change' }
        ]
      },
      options: [
        {
          label: '选项一',
          value: '选项一'
        },
        {
          label: '选项二',
          value: '选项二'
        }
      ],
      isDisabled: false,
      formInline: {
        demand: undefined
      },
      jxInputData: [],
      jxTableLoading: false,
      jxTableKey: '',
      // 关于表格添加
      enterVisible: false,
      enterForm: {
        mbbh: '',
        pointJd: '',
        pointWd: ''
      },
      enterRules: {
        mbbh: [{ required: true, message: '请输入目标编号', trigger: 'blur' }],
        pointJd: [
          { required: true, message: '请输入经度', trigger: 'blur' },
          {
            validator: this.jdCoolarInfo,
            message: '经度格式不正确',
            trigger: 'blur'
          }
        ],
        pointWd: [
          { required: true, message: '请输入纬度', trigger: 'blur' },
          {
            validator: this.wdCoolarInfo,
            message: '纬度格式不正确',
            trigger: 'blur'
          }
        ]
      },
      isShowCor: false,
      fileRef: undefined,
      zhlxOptions: [
        { label: '光学', value: '光学' },
        { label: 'SAR', value: 'SAR' },
      ],
      isFullLoading: null
    }
  },
  watch: {
    visiable: {
      handler(val) {
        if (val == false) {
          this.isDisabled = false
        }
      }
    }
  },
  mounted() {
    this.$bus.$on('openLeft', (data, flag) => {
      this.$store.dispatch('drawer/setleftvisible', true)
      this.visiable = true
      this.formData = data
      this.isDisabled = flag
      this.formData.wgbh = JSON.parse(data.wgbh)
      this.formData.wxlb = JSON.parse(data.wxlb)
    })
  },
  methods: {
    //显示输入的经纬度坐标
    displayCoordinates() {
      this.isShowCor = !this.isShowCor
      const handleData = this.jxInputData.map(item => {
        return {
          longitude: parseFloat(item.pointJd),
          latitude: parseFloat(item.pointWd)
        }
      })

      this.$bus.$emit('showCoordinate', handleData, this.isShowCor)
    },
    // 添加卫星列表
    addSatellite() {
      this.formData.wxlb.push({
        wxlb: ''
      })
    },
    // 删除卫星列表单个
    handleRemoveSatellite(rowV, index) {
      this.formData.wxlb.splice(index, 1)
    },
    // 添加网格编号
    addGrid() {
      this.formData.wgbh.push({
        wgbh: ''
      })
    },
    // 删除网格编号单个
    handleRemoveGrid(rowV, index) {
      this.formData.wgbh.splice(index, 1)
    },
    handleAdd() {
      this.formData.mbzbList.push({
        pointJd: '',
        pointWd: ''
      })
    },
    handleRemove(row, index) {
      this.jxInputData.splice(index, 1)
    },
    // 关闭弹窗清空输入框
    clearFields() {
      if (!this.visiable) {
        this.$refs.ruleForm.resetFields()
        this.formData.mbzbList = []
        this.formData.wgbh = []
        this.formData.wxlb = []
        this.jxInputData = []
        this.$refs.formInlineRef.resetFields()
        this.$bus.$emit('showCoordinate', [], false)
      }
    },

    /** 保存推理应用 */
    programevaluation(formName) {
      this.$refs[formName].validate(valid => {
        if (!valid) {
          return false
        }

        if (compareDates(this.formData.xqkssj, this.formData.xqjssj) == false) {
          this.$message({
            type: 'warning',
            message: '需求结束时间不能小于需求开始时间'
          })
          return false
        }

        if (this.jxInputData.length == 0) {
          this.$message({
            type: 'warning',
            message: '请上传目标经纬度数据'
          })
          return false
        }

        if (this.formData.zhlx == '' || this.formData.gzms == '' || this.formData.fbl == '' || this.formData.yxj == '') {
          this.$message({
            type: 'warning',
            message: '请先进行知识图谱推理'
          })
          return false
        }
        // 经纬度数据列表
        this.formData.gcxqPointList = this.jxInputData
        this.$message.warning("正在保存")
        this.isFullLoading = this.$loading({
          lock: true,
          text: '正在进行知识图谱推理',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        SavePlanTasks(this.formData).then(response => {
          if (response.data.code !== 200) {
            this.$message({
              type: 'error',
              message: '操作失败'
            })
            this.isFullLoading.close()
            return
          }
          this.visiable = false
          this.clearFields()
          this.$store.dispatch('drawer/setleftvisible', false)
          this.$bus.$emit("openRight", true)
          this.isFullLoading.close()
          this.$message({
            type: 'success',
            message: '操作成功'
          })
        })
      })
    },

    /** 关于上传 */
    // 解析excel文件
    jxExcelFile() {
      this.jxTableLoading = true
      const fileInput = this.fileRef
      if (fileInput.files.length > 0) {
        const file = fileInput.files[0]
        const formData = new FormData()
        formData.append('file', file)
        formData.append('type', '1')
        UploadExcel(formData).then(res => {
          if (res.data.code === 200) {
            const data = res.data
            this.jxInputData = data.data
            this.jxTableKey = Math.random()
            this.jxTableLoading = false
            this.fileRef.remove() // 上传完成后，删除这个DOM元素
          }
        })
      }
    },

    // 监听上传的回调
    uploadFileChange(event) {
      let that = this
      if (event.target.files.length > 0) {
        const file = event.target.files[0]
        that.formInline.demand = file.name
      }
    },
    // 选择需要上传的文件
    selectWjButton() {
      let that = this
      // 创建一个input标签
      that.fileRef = document.createElement('input')
      // 设置input标签的属性
      that.fileRef.name = 'file'
      // 设置input标签的样式
      that.fileRef.type = 'file'
      // 设置input标签的属性
      that.fileRef.accept = '.xls,.xlsx'
      // 设置input标签的样式
      that.fileRef.style.display = 'none'
      // 将input标签添加到body中
      that.fileRef.click()
      document.body.appendChild(that.fileRef)
      // 监听用户选择文件后的操作
      that.fileRef.addEventListener('change', that.uploadFileChange, false)
    },

    /** 关于表格添加 */
    /** 经度校验 */
    jdCoolarInfo(rule, value, callback) {
      const coordinateRegex = /^[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)$/
      if (coordinateRegex.test(value)) {
        callback()
      } else {
        callback(new Error('经度格式不正确'))
      }
    },

    /** 纬度校验 */
    wdCoolarInfo(rule, value, callback) {
      const coordinateRegex = /^[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?)$/
      if (coordinateRegex.test(value)) {
        callback()
      } else {
        callback(new Error('经度格式不正确'))
      }
    },

    /** 删除单行数据 */
    handleRemoveXq(row, index) {
      that.jxInputData.splice(index, 1)
    },

    /** 打开弹窗 */
    OpenAddModal() {
      this.enterForm = {
        mbbh: '',
        pointJd: '',
        pointWd: ''
      }
      this.enterVisible = true
    },

    /** 确定 */
    addXq(formName) {
      this.$refs[formName].validate(valid => {
        if (!valid) return false
        this.jxInputData.push(this.enterForm)
        this.enterVisible = false
      })
    },

    /** 取消 */
    cancel(formName) {
      this.$refs[formName].resetFields()
      this.enterVisible = false
    },

    /** 智能决策 */
    handleDecision() {
      if (
        !this.formData.rwlx ||
        !this.formData.mbxt ||
        !this.formData.qxtj ||
        !this.formData.gjys ||
        !this.formData.sfhzmb ||
        !this.formData.xqkssj ||
        !this.formData.xqjssj
      ) {
        this.$message({
          type: 'warning',
          message: '请先填写任务信息'
        })
        return
      }
      const params = {
        type: '2',
        znjcJsonStr: JSON.stringify(this.formData).replace(/\"/g, "'")
      }
      CallIntelligentDecision(params).then(response => {
        if (response.data.code !== 200) {
          this.$message({
            type: 'error',
            message: '操作失败'
          })
          return
        }

        const toParse = JSON.parse(response.data.message)
        this.formData.zhlx = toParse.zhlx
        this.formData.gzms = toParse.gcms
        this.formData.fbl = toParse.fbl
        this.formData.yxj = toParse.yxj
      })
    }
  },
  beforeDestroy() {
    this.$bus.$off('openLeft')
  }
}
